import java.util.Arrays;

import lejos.nxt.Battery;
import lejos.nxt.LightSensor;
import lejos.nxt.SensorPort;
import lejos.nxt.TouchSensor;
import lejos.nxt.UltrasonicSensor;

public class Starter {
	
	public static int lightValue, speed;
	
	public static void main(String[] args) throws Exception {
		
		if (!EngineCheck.startToCheck()) return;
		
		UltrasonicSensor ultrasonic = new UltrasonicSensor(Eyes.ULTRASONIC_PORT);
		LightSensor ls = new LightSensor(Tapefinder.LIGHT_PORT);
		TouchSensors touch = new TouchSensors();
		Modes mode = new Modes();
		Eyes eyes = new Eyes(ultrasonic, 60, 10);		
		
		int[] lightValues = new int[36];
		int tolerance;
		
		mode.chooseMode();
		speed = mode.getSpeed();
		Thread.sleep(3000);
		
		for(int i = 0; i < lightValues.length; i++){
			lightValues[i]=ls.getLightValue();
			Moves.turnLeftAtSpot(20);
		}
		
		Arrays.sort(lightValues);
		tolerance = ((lightValues[0] - lightValues[lightValues.length - 1]) / 2) + 15;

		Tapefinder tape = new Tapefinder(ls, ls.getLightValue(), tolerance);
		Moves.ULTRASONIC_MOTOR.resetTachoCount();
		
		
		while(Battery.getVoltage() > 5){
			/**
			 * THIS IS THE LOOP THAT SHOULD RUN THE SENSOR-CHECKS!
			 */
			
			if(eyes.obstacle()) eyes.avoidDanger();
			if(tape.tapeFound()) break;
			touch.avoidDanger();
			Moves.forward(speed);
			
		}
		tape.avoidDanger();	//After while end, check if it is because of the tape.
		
		
		Alarm.playSoundAlarm();
		Moves.backward(500);
		Alarm.playSoundAlarm();
		Moves.backward(500);
		Alarm.playSoundAlarm();
		Moves.stop();
	}
}	
